package eyer.jmx;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.management.Attribute;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

public class JmxConn {
    private JMXConnector conn;
    private String name;

    public String getName() {
        return name;
    }

    public JmxConn(String name, JMXConnector conn) {
        this.name = name;
        this.conn = conn;
    }

    public void close() throws IOException {
        if (conn != null) {
            conn.close();
        }
    }

    public Map<String, Object> getAttrs(String objectName) throws JmxClientException {
        try {
            Map<String, Object> r = new HashMap<String, Object>();
            MBeanServerConnection mbsc = conn.getMBeanServerConnection();

            ObjectName on = new ObjectName(objectName);
            MBeanInfo info = mbsc.getMBeanInfo(on);

            MBeanAttributeInfo[] attrs = info.getAttributes();
            String[] attributes = new String[attrs.length];
            for (int i = 0; i < attributes.length; i++) {
                attributes[i] = attrs[i].getName();
            }

            List<Attribute> list = mbsc.getAttributes(on, attributes).asList();
            for (Attribute one : list) {
                r.put(one.getName(), one.getValue());
            }

            return r;
        } catch (Exception e) {
            throw new JmxClientException("get-attrs-error", e);
        }
    }
}
